import React, { useEffect, useState, useCallback, useMemo } from 'react';
import {
  Table,
  Button,
  Card,
  Modal,
  Form,
  Input,
  message,
  Switch,
  Descriptions,
  Space,
  Typography,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table';
import { ApiTokenItem } from 'admin/schema/Cas';
import {
  getApiTokens,
  addApiToken,
  deleteApiToken,
  updateApiTokenStatus,
  updateApiTokenExpirationTime,
  getCasOrganizationsShow,
} from 'admin/servers/modules/Cas';
import { useSelector } from 'react-redux';
import { CopyOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { debounce } from 'lodash';

interface ApiTokenFormValues {
  name: string;
  org: string;
  description: string;
  expireTime: moment.Moment;
}

const { confirm } = Modal;

const { Paragraph } = Typography;

const ApiToken: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [tokens, setTokens] = useState<ApiTokenItem[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增API令牌');
  const [form] = Form.useForm<ApiTokenFormValues>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [organizations, setOrganizations] = useState<any[]>([]);
  const userInfo = useSelector((state: any) => state.loginInfo);
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [currentToken, setCurrentToken] = useState<ApiTokenItem | null>(null);

  // const treeData = useMemo(() => {
  //   return convertToTree(organizations);
  // }, [organizations]);
  // 获取单位列表
  const fetchOrganizations = useCallback(async () => {
    try {
      const response = await getCasOrganizationsShow();
      if (response.status === 200) {
        setOrganizations(response.data);
      }
    } catch (error) {
      console.error('获取单位列表失败:', error);
    }
  }, []);

  // 获取API令牌列表
  const fetchTokens = useCallback(async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await getApiTokens(page - 1, pageSize);
      if (response.status === 200) {
        const { content, totalElements, number } = response.data;
        setTokens(content);
        setPagination(prev => ({
          ...prev,
          pageSize,
          current: number + 1,
          total: totalElements,
        }));
      }
    } catch (error) {
      console.error('获取API令牌列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTokens();
    fetchOrganizations();
  }, [fetchTokens, fetchOrganizations]);

  // 处理表格变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchTokens(newPagination.current, newPagination.pageSize);
  };

  // 处理新增按钮点击
  const handleAdd = () => {
    setModalTitle('新增API令牌');
    form.resetFields();
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (record: ApiTokenItem) => {
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除这个API令牌吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deleteApiToken(record.id);
          if (response.status === 200) {
            message.success('删除成功');
            fetchTokens(pagination.current);
          }
        } catch (error) {
          console.error('删除API令牌失败:', error);
        }
      },
    });
  };

  // 处理状态切换
  const handleStatusChange = async (checked: boolean, record: ApiTokenItem) => {
    try {
      const response = await updateApiTokenStatus(checked, record.id);
      if (response.status === 200) {
        message.success('状态更新成功');
        fetchTokens(pagination.current);
      }
    } catch (error) {
      console.error('更新API令牌状态失败:', error);
    }
  };

  // 处理有效期更新
  const handleExpirationChange = async (value: moment.Moment | null, record: ApiTokenItem) => {
    if (!value) return;
    try {
      const response = await updateApiTokenExpirationTime(
        value.format('YYYY-MM-DD HH:mm:ss'),
        record.id
      );
      if (response.status === 200) {
        message.success('有效期更新成功');
        fetchTokens(pagination.current);
      }
    } catch (error) {
      console.error('更新API令牌有效期失败:', error);
    }
  };

  // 处理模态框确认
  const handleModalOk = debounce(async () => {
    try {
      const values = await form.validateFields();

      const response = await addApiToken({
        name: values.name,
        org: userInfo.orgId,
        description: values.description,
        userId: userInfo.id,
        enabled: true,
      });
      if (response.status === 200) {
        message.success('添加成功');
        setModalVisible(false);
        fetchTokens();
      }
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  }, 500);

  // 处理查看详情
  const handleView = (record: ApiTokenItem) => {
    setCurrentToken(record);
    setViewModalVisible(true);
  };

  const columns: ColumnsType<ApiTokenItem> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '单位',
      dataIndex: 'org',
      key: 'org',
      render: (org: string) => {
        const orgItem = organizations.find(item => item.id === org);
        return orgItem ? orgItem.name : '-';
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: number) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '最后访问时间',
      dataIndex: 'lastAccessTime',
      key: 'lastAccessTime',
      render: (time: string) => (time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled: boolean, record: ApiTokenItem) => (
        <Switch
          checked={enabled}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={checked => handleStatusChange(checked, record)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
          <Button type="link" danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" onClick={handleAdd}>
            新增API令牌
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={tokens}
          rowKey="id"
          pagination={{
            ...pagination,
            showTotal: (total: number) => `共 ${total} 条`,
            showSizeChanger: true,
          }}
          loading={loading}
          onChange={handleTableChange}
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
        maskClosable={false}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[
              { required: true, message: '请输入名称' },
              { max: 60, message: '最大长度为60位字符' },
            ]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>

          {/* <Form.Item name="org" label="单位" rules={[{ required: true, message: '请选择单位' }]}>
            <TreeSelect
              showSearch
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="请选择单位"
              allowClear
              treeDefaultExpandAll
              treeData={treeData}
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            />
          </Form.Item> */}

          <Form.Item
            name="description"
            label="描述"
            rules={[
              { required: true, message: '请输入描述' },
              { max: 255, message: '最大长度为255位字符' },
            ]}
          >
            <Input.TextArea placeholder="请输入描述" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="查看API令牌详情"
        visible={viewModalVisible}
        onCancel={() => setViewModalVisible(false)}
        footer={null}
        width={800}
      >
        <Descriptions column={2} bordered>
          <Descriptions.Item label="名称" span={2}>
            {currentToken?.name}
          </Descriptions.Item>
          <Descriptions.Item label="单位" span={2}>
            {organizations.find(item => item.id === currentToken?.org)?.name || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="描述" span={2}>
            {currentToken?.description}
          </Descriptions.Item>
          <Descriptions.Item label="Token" span={2}>
            <Paragraph style={{ margin: 0 }} copyable>
              {currentToken?.token}
            </Paragraph>
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {currentToken?.createTime
              ? moment(currentToken.createTime).format('YYYY-MM-DD HH:mm:ss')
              : '-'}
          </Descriptions.Item>
          {/* <Descriptions.Item label="创建人">{currentToken?.createBy || '-'}</Descriptions.Item> */}
          <Descriptions.Item label="状态">
            {currentToken?.enabled ? '启用' : '禁用'}
          </Descriptions.Item>
          <Descriptions.Item label="最后访问时间">
            {currentToken?.lastAccessTime
              ? moment(currentToken.lastAccessTime).format('YYYY-MM-DD HH:mm:ss')
              : '-'}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
    </div>
  );
};

export default ApiToken;
